package com.ruoyi.web.controller.sm;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.School;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISchoolService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 学校信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/sm/sm")
public class SchoolController extends BaseController {
    @Resource
    private ISchoolService schoolService;


    @Autowired
    private ISysUserService userService;

    @PostMapping("/importData")
    public AjaxResult importData(
            @RequestParam("file") MultipartFile file,
            @RequestParam("updateSupport") boolean updateSupport
    ) throws Exception {
        ExcelUtil<School> util = new ExcelUtil<School>(School.class);
        List<School> list = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = schoolService.importSchool(list, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<School> util = new ExcelUtil<School>(School.class);
        util.importTemplateExcel(response, "学校数据");
    }

    @PreAuthorize("@ss.hasPermi('sm:school:list')")
    @GetMapping("/list")
    public TableDataInfo list(School school) {
        startPage();
        List<School> list = schoolService.selectSchoolList(school);
        return getDataTable(list);
    }

    @Log(title = "学校管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('sm:school:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, School school) {
        List<School> list = schoolService.selectSchoolList(school);
        ExcelUtil<School> util = new ExcelUtil<School>(School.class);
        util.exportExcel(response, list, "学校数据");
    }

    /**
     * 根据学校编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('sm:school:query')")
    @GetMapping(value = "/{schoolId}")
    public AjaxResult getInfo(@PathVariable Long schoolId) {
        return success(schoolService.selectSchoolById(schoolId));
    }

    /**
     * 新增学校
     */
    @PreAuthorize("@ss.hasPermi('sm:school:add')")
    @Log(title = "学校管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestParam("schoolName") String schoolName,
                          @RequestParam("schoolType") String schoolType,
                          @RequestParam(value = "schoolLocation", required = false) String schoolLocation, @RequestPart(value = "sceneryImages", required = false) MultipartFile[] sceneryImages) throws Exception {
        School school = new School();
        school.setSchoolName(schoolName);
        school.setSchoolType(schoolType);
        school.setSchoolLocation(schoolLocation);
        //处理文件上传
        if (sceneryImages != null && sceneryImages.length > 0) {
            List<String> imageUrls = new ArrayList<>();
            for (MultipartFile sceneryFile : sceneryImages) {
                String avatar = FileUploadUtils.upload(RuoYiConfig.getSceneryPath(), sceneryFile, MimeTypeUtils.IMAGE_EXTENSION);
                imageUrls.add(avatar);
            }
            school.setSceneryImages(imageUrls);
        }
        school.setCreateBy(getUsername());
        return toAjax(schoolService.insertSchool(school));

    }

    /**
     * 修改保存学校
     */
    @PreAuthorize("@ss.hasPermi('sm:school:edit')")
    @Log(title = "学校管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestParam("schoolName") String schoolName,
                           @RequestParam("id") Long schoolId,
                           @RequestParam("schoolType") String schoolType,
                           @RequestParam("deletedImages") String deletedImages,
                           @RequestParam(value = "schoolLocation", required = false) String schoolLocation, @RequestPart(value = "sceneryImages", required = false) MultipartFile[] sceneryImages) throws Exception {
        School school = new School();
        school.setId(schoolId);
        school.setSchoolName(schoolName);
        school.setSchoolType(schoolType);
        school.setSchoolLocation(schoolLocation);
        // 获取现有学校信息
        School existingSchool = schoolService.selectSchoolById(schoolId);
        List<String> imageUrls = new ArrayList<>();

        // 保留未被删除的旧图片
        if (existingSchool.getSceneryImages() != null && !existingSchool.getSceneryImages().isEmpty()) {
            List<String> existingImages = existingSchool.getSceneryImages();
            List<String> imagesToDelete = deletedImages != null ? Arrays.asList(deletedImages.split(",")) : new ArrayList<>();

            for (String image : existingImages) {
                if (!imagesToDelete.contains(image)) {
                    imageUrls.add(image);
                }
            }
        }
        //处理文件上传
        if (sceneryImages != null) {
            for (MultipartFile sceneryFile : sceneryImages) {
                String avatar = FileUploadUtils.upload(RuoYiConfig.getSceneryPath(), sceneryFile, MimeTypeUtils.IMAGE_EXTENSION);
                imageUrls.add(avatar);
            }
        }
        school.setSceneryImages(imageUrls);
        schoolService.updateSchool(school);
        return success();
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('sm:school:edit')")
    @Log(title = "学校管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody School school) {
        schoolService.checkSchoolAllowed(school);
        return toAjax(schoolService.authDataScope(school));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('sm:school:edit')")
    @Log(title = "学校管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody School school) {
        schoolService.checkSchoolAllowed(school);
        school.setUpdateBy(getUsername());
        return toAjax(schoolService.updateSchoolStatus(school));
    }

    /**
     * 删除学校
     */
    @PreAuthorize("@ss.hasPermi('sm:school:remove')")
    @Log(title = "学校管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{schoolIds}")
    public AjaxResult remove(@PathVariable Long[] schoolIds) {
        return toAjax(schoolService.deleteSchoolByIds(schoolIds));
    }

    /**
     * 获取学校选择框列表
     */
    @PreAuthorize("@ss.hasPermi('sm:school:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        return success(schoolService.selectSchoolAll());
    }

    /**
     * 查询已分配用户学校列表
     */
    @PreAuthorize("@ss.hasPermi('sm:school:list')")
    @GetMapping("/authUser/allocatedList")
    public TableDataInfo allocatedList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectAllocatedList(user);
        return getDataTable(list);
    }


}
